package com.cszy.ewmxns.base

import android.os.Bundle
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.cszy.ewmxns.ext.toast


import java.lang.reflect.ParameterizedType

abstract class BaseVMFragment<VM : BaseViewModel, VB : ViewBinding> : BaseFragment<VB, Any?>() {

    lateinit var mViewModel: VM

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        createViewModel()
        lifecycle.addObserver(mViewModel)
        registerEvent()
        super.onViewCreated(view, savedInstanceState)
    }

    /**
     * 注册事件
     */
    private fun registerEvent() {
        mViewModel.ui.showDialog.observe(viewLifecycleOwner) {
            showLoading(it)
        }
        mViewModel.ui.dismissDialog.observe(viewLifecycleOwner) {
            dismissLoading()
        }
        mViewModel.ui.toast.observe(viewLifecycleOwner) {
            toast(it)
        }
        mViewModel.ui.msgEvent.observe(viewLifecycleOwner) {
            handleEvent(it)
        }
    }

    /**
     * 创建 ViewModel
     * 共享 ViewModel的时候,重写Fragment的getViewModelStore()方法，
     * 返回 activity的ViewModelStore或者父Fragment的ViewModelStore
     */
    @Suppress("UNCHECKED_CAST")
    private fun createViewModel() {
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            val tp = type.actualTypeArguments[0]
            val tClass = tp as? Class<VM> ?: BaseViewModel::class.java
            mViewModel = ViewModelProvider(this)[tClass] as VM
        }
    }

}